'use strict';
var cheerio = require('cheerio');

// http://stackoverflow.com/questions/14480345/how-to-get-the-nth-occurrence-in-a-string
function getPosition(str, m, i) {
  return str.split(m, i).join(m).length;
}

hexo.extend.filter.register('after_post_render', function(data){
  var config = hexo.config;
  var toprocess = ['excerpt', 'more', 'content'];
  if (!config.images_settle){
    return;
  }
  for(var i = 0; i < toprocess.length; i++){
    var key = toprocess[i];
    var $ = cheerio.load(data[key], {
      ignoreWhitespace: false,
      xmlMode: false,
      lowerCaseTags: false,
      decodeEntities: false
    });
    $('img').each(function(){
      if ($(this).attr('src')){
        // For windows style path, we replace '\' to '/'.
        console.info&&console.info("update link origin:-->"+ $(this).attr('src'));
        var src = $(this).attr('src').replace('\\', '/');
        if(!(/http[s]*.*|\/\/.*/.test(src))) {//只要非http/https的内容
          var dirIndex = src.lastIndexOf("/");
          var filename= src.substring(dirIndex+1);
          if (config.images_path&&config.images_path!=''){
            if (config.images_path.lastIndexOf("/") != config.images_path.length - 1){
              $(this).attr('src', config.images_path + "/" + filename);
            }else {
              console.info&&console.info("update link as config.images_path:-->"+(config.images_path + filename));
              $(this).attr('src', config.images_path + filename);
            }
          }else {
            $(this).attr('src', filename);
          }
          // console.info&&console.info("update link as filename:-->"+filename);
        }
      }else{
        console.info&&console.info("no src attr, skipped...");
        // console.info&&console.info($(this));
      }
    });
    data[key] = $.html();
  }
});